﻿Create Procedure [dbo].[accounts_user_delete_user]
-- --------------------------------------------------------------------------------- 
-- Procedure Name: accounts_user_delete_user
--
-- Description: Deletes a specified user
--
--
--
-- Version  Date          Author           Description
-- ---------------------------------------------------------------------------------
--  1       19-Jan-2012   The Collective   Created procedure
-- 
--
--
--
-- ---------------------------------------------------------------------------------
-- ---------------------------------------------------------------------------------
(@UserGUIDtoDelete as uniqueidentifier, 
@SecurityCurrentUsername as varchar(255),
@returncode as int output,
@returnmessage as varchar(200) output )
AS
BEGIN

    set nocount on
    Declare @SecurityCurrentUserGuid Uniqueidentifier;
    
    -- Get the guid for the username of the logged in user
    Select @SecurityCurrentUserGuid = User_GUID from Accounts_User where username = @SecurityCurrentUsername;
    
    -- Check that the current user is admin
    If not exists(Select user_GUID from Accounts_User_Roles where User_GUID =  @SecurityCurrentUserGuid and RoleNumber = 101)
       Begin
          -- Exit if user does not have permission
          Set @returncode = 1;
          Set @returnmessage = 'Error. Logged in user is not an administrator';
	      Return 1;
       End;
    
    begin try
        -- Delete the user
        Begin Transaction delete_user_transaction;        
        Delete from Accounts_User_roles where User_GUID = @UserGUIDtoDelete;
        Delete from Accounts_User_Normal_Permissions where User_GUID = @UserGUIDtoDelete;
        Delete from Accounts_User_Details where User_GUID = @UserGUIDtoDelete;
        Delete from Accounts_User where User_GUID = @UserGUIDtoDelete;    
        Commit Transaction delete_user_transaction;  
        
        Set @returncode = 0;
        Set @returnmessage = 'Successfully deleted record.';      
    end try
    begin catch
        -- If an error occurs then rollback
        Rollback Transaction delete_user_transaction;
        
        Set @returncode = 1;
        Set @returnmessage = 'Unknown database error occurred.';  
    end catch
    
    set nocount off
    
    Return 0;

END;